package models

import (
	"gin-project/config"
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// Token 令牌模型
type Token struct {
	gorm.Model // gorm.Model 包含了 ID, CreatedAt, UpdatedAt, DeletedAt 
	UserID    uint      `gorm:"not null;index" json:"user_id"`
	Token     string    `gorm:"size:36;uniqueIndex;not null" json:"token"`
	ExpiresAt time.Time `gorm:"not null" json:"expires_at"`
}

func GenerateToken(userID uint)(*Token,error){
	//生成uuid
	tokenStr := uuid.New().String()

	//计算过期时间
	expiresAt := time.Now().Add(time.Duration(config.AppConfig.TokenExpiryHours) * time.Hour)

	token := &Token{
		UserID:    userID,
		Token:     tokenStr,
		ExpiresAt: expiresAt,
	}
	//先删除旧的令牌
	DeleteToken(tokenStr)
	// 保存令牌到数据库
	if err := config.DB.Create(token).Error; err !=nil{
		return nil,err
	}
	return token,nil
}
// ValidateToken 验证令牌是否有效
func ValidateToken(tokenStr string) (*Token, error){
	var token Token
	result := config.DB.Where("token = ? and expires_at > ?",
			tokenStr,time.Now()).First(&token) // 关键：去掉默认的 ORDER BY id 
	if result.Error != nil {
		return nil, result.Error
	}
	return &token, nil
}

// DeleteToken 注销令牌
func DeleteToken(tokenStr string) error{
	return config.DB.Unscoped().Where("token =?",tokenStr).Delete(&Token{}).Error
}
// DeleteExpiredTokens 清理过期令牌
func DeleteExpiredTokens() error{
	return config.DB.Where("expires_at <= ?", time.Now()).Delete(&Token{}).Error
}